//
//  BLPhotoContainView.m
//  Byelone
//
//  Created by Qi Liu on 2021/2/17.
//

#import "BLPhotoContainView.h"
#import <FLAnimatedImage/FLAnimatedImageView.h>
#import "NSData+ImageContentType.h"
#import "SDImageCache.h"
#import "YBImageBrowser.h"

#define XXPhotoMargin 10
@interface BLPhotoContainView ()<YBImageBrowserDelegate>

@property (nonatomic, strong) NSMutableArray *imageViewsArray;
@property(nonatomic,strong)NSMutableDictionary  <NSNumber*,FLAnimatedImageView*>* gifDic;
@property(nonatomic,assign)bool isAnimateing;
@property(nonatomic,assign)bool isCompleted;
@property(nonatomic,strong)NSArray <NSNumber *>* sortKeys;

@end

@implementation BLPhotoContainView

-(NSMutableDictionary<NSNumber *,FLAnimatedImageView *> *)gifDic{
    if (_gifDic == nil) {
        _gifDic = [NSMutableDictionary dictionary];
    }
    return _gifDic;
}

#pragma mark - private actions

-(void)setImageArray{
    if (_picPathStringsArray.count>0) {
        
        self.imageViewsArray = [NSMutableArray array];
        for (int i = 0; i < _picPathStringsArray.count; i++) {
            FLAnimatedImageView * imageView = [[FLAnimatedImageView alloc]init];
            imageView.userInteractionEnabled = YES;
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            imageView.tag = i;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewClick:)];
            [imageView addGestureRecognizer:tap];
            [self addSubview:imageView];
            [self.imageViewsArray addObject:imageView];
        }
    }
}

- (void)removeAll{
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
}

-(CGFloat)getHightWIthArray:(NSArray *)picPathStringsArray{
    
    _picPathStringsArray = picPathStringsArray;
    
    CGFloat containview_H = 0;
    
    if (picPathStringsArray.count == 0) {
        return containview_H;
    }
    
    [self setImageArray];
    
    NSInteger window_W = BL_WINDOW_WIDTH - 51;
    
    if (picPathStringsArray.count == 1) {
        URLModel * model = [picPathStringsArray firstObject];
        float height = [model.height floatValue];
        float width = [model.width integerValue];
        CGFloat scale = height / width;
        if (height > width) {
            if (height > window_W) {
                height = window_W;
            }
            width = height/scale;
            
        }else if (height == width){
            if (height > window_W) {
                height = window_W;
            }
            width = height;
            
        }else{
            if (width > window_W) {
                width = window_W;
            }
            height = width * scale;
        }
        
        FLAnimatedImageView * image = [self .imageViewsArray firstObject];
        image.frame = CGRectMake(10.5, 0, width, height);
        containview_H = height;
        
    }else if(picPathStringsArray.count ==2){
        CGFloat viewW = (BL_WINDOW_WIDTH - 51)/2;
        FLAnimatedImageView * leftView = [self.imageViewsArray firstObject];
        leftView.frame = CGRectMake(10.5, 0, viewW, viewW);
        FLAnimatedImageView * rightView = [self.imageViewsArray lastObject];
        rightView.frame = CGRectMake(10.5 + viewW, 0, viewW, viewW);
        containview_H = viewW;
        
    }else{
        
        CGFloat gap = 12.5;
        NSInteger viewW_H = (BL_WINDOW_WIDTH - 51 - 2 * gap)/3;
        
        for (int i = 0; i<picPathStringsArray.count; i++) {
            NSInteger row = i % 3;
            NSInteger line = i / 3;
            FLAnimatedImageView * flView = [self.imageViewsArray objectAtIndex:i];
            flView.frame = CGRectMake(10.5 + (viewW_H + gap) * row, line * (viewW_H + gap), viewW_H, viewW_H);
            
            if (i == picPathStringsArray.count -1) {
                containview_H = CGRectGetMaxY(flView.frame);
            }
        }
    }
    
    [self handelImage];
    
    return containview_H;
}

-(void)handelImage{
    //配置完尺寸 加载图片
    
    dispatch_group_t group =dispatch_group_create();
    for(int i = 0; i < self.picPathStringsArray.count; i++){
        
        FLAnimatedImageView * imageView = [_imageViewsArray objectAtIndex:i];
        dispatch_group_enter(group);
        URLModel * model = [self.picPathStringsArray objectAtIndex:i];
        NSURL * url = [NSURL URLWithString:model.momentUrl];
        [imageView sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            dispatch_group_leave(group);
            if (error) {return ; }
            [self imageLoadFinish:imageURL imageView:imageView];
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        [self sortGifdic];
        [self loopPlayGifWithIndex:0];
    });
}


-(void)setPicPathStringsArray:(NSArray *)picPathStringsArray{
    
    _picPathStringsArray = picPathStringsArray;
    
    if (picPathStringsArray.count == 0) {
        self.height = 0;
        return;
    }
    [self setImageArray];
    
    NSInteger window_W = BL_WINDOW_WIDTH - 30;
    if (picPathStringsArray.count == 1) {
        URLModel * model = [picPathStringsArray firstObject];
        float height = [model.height floatValue];
        float width = [model.width integerValue];
        CGFloat scale = height / width;
        if (height > width) {
            if (height > window_W) {
                height = window_W;
            }
            width = height/scale;
            
        }else if (height == width){
            if (height > window_W) {
                height = window_W;
            }
            width = height;
            
        }else{
            if (width > window_W) {
                width = window_W;
            }
            height = width * scale;
        }
        
        FLAnimatedImageView * image = [self .imageViewsArray firstObject];
        self.height = height;
        image.frame = CGRectMake(10.5, 0, width, height);
        
    }else if(picPathStringsArray.count ==2){
        CGFloat viewW = (BL_WINDOW_WIDTH - 51)/2;
        FLAnimatedImageView * leftView = [self.imageViewsArray firstObject];
        leftView.frame = CGRectMake(10.5, 0, viewW, viewW);
        FLAnimatedImageView * rightView = [self.imageViewsArray lastObject];
        rightView.frame = CGRectMake(10.5 + viewW, 0, viewW, viewW);
        
        self.height = viewW ;
        
    }else{
        NSInteger viewW_H = (BL_WINDOW_WIDTH - 51)/3;
        CGFloat gap = 12.5;
        
        for (int i = 0; i<picPathStringsArray.count; i++) {
            NSInteger row = i % 3;
            NSInteger line = i / 3;
            FLAnimatedImageView * flView = [self.imageViewsArray objectAtIndex:i];
            flView.frame = CGRectMake(10.5 + (viewW_H + gap) * row, line * (viewW_H + gap), viewW_H, viewW_H);
            
            if (i == picPathStringsArray.count -1) {
                self.height = CGRectGetMaxY(flView.frame);
            }
        }
    }
    
    
    //配置完尺寸 加载图片
    
    dispatch_group_t group =dispatch_group_create();
    for(int i = 0; i < self.picPathStringsArray.count; i++){
        
        FLAnimatedImageView * imageView = [_imageViewsArray objectAtIndex:i];
        imageView.layer.cornerRadius = 5;
        imageView.layer.masksToBounds = YES;
        
        dispatch_group_enter(group);
        URLModel * model = [self.picPathStringsArray objectAtIndex:i];
        NSURL * url = [NSURL URLWithString:model.momentUrl];
        [imageView sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            dispatch_group_leave(group);
            if (error) {return ; }
            [self imageLoadFinish:imageURL imageView:imageView];
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        [self sortGifdic];
        [self loopPlayGifWithIndex:0];
    });
    
}

-(void)imageLoadFinish:(NSURL *)url imageView:(FLAnimatedImageView *)imageView {
    
    NSData * imageData = [self getCacheImageDataForModel:url];
    SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:imageData];
    if (imageFormat == SDImageFormatGIF) {
        self.gifDic[@(imageView.tag)] = imageView;
        [imageView stopAnimating];
    } else {
        
    }
}

- (NSData *)getCacheImageDataForModel:(NSURL *)url {
    
    SDImageCache * imageCache = [SDImageCache sharedImageCache];
    NSString*cacheImageKey = [[SDWebImageManager sharedManager]cacheKeyForURL:url];
    NSString *defaultPath = [imageCache cachePathForKey:cacheImageKey];
    //    [imageCache defaultCachePathForKey:cacheImageKey];
    NSData *data = [NSData dataWithContentsOfFile:defaultPath];
    if (data) {
        return data;
    }else{
        return  nil;
    }
}
-(void)sortGifdic{
    if (self.gifDic.count==0) { return ; }
    _sortKeys = [self.gifDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    NSLog(@"排序");
}

-(void)loopPlayGifWithIndex:(NSInteger)index{
    if (self.gifDic.count==0) { return; }
    self.isCompleted = true;
    self.isAnimateing = true;
    NSNumber * key = _sortKeys[index];
    FLAnimatedImageView * imageV = self.gifDic[key];
    __weak typeof(FLAnimatedImageView *)weakImagev = imageV;
    __weak typeof(NSArray<NSNumber*> *)weakSortKeys = _sortKeys;
    [imageV startAnimating];
    imageV.loopCompletionBlock = ^(NSUInteger loopCountRemaining) {
        [weakImagev stopAnimating ];
        NSInteger nextindex = index+1== weakSortKeys.count? 0: index+1;
        [self loopPlayGifWithIndex: nextindex];
    };
}

-(void)startAllGifAnimating{
    if (!_isCompleted || _isAnimateing) {  return; }
    [self loopPlayGifWithIndex:0];
}

-(void)stopAllGifAnimating{
    if(!self.isAnimateing)return;
    
    if (!NSThread.isMainThread) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.gifDic enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, FLAnimatedImageView * _Nonnull obj, BOOL * _Nonnull stop) {
                [obj stopAnimating];
            }];
            self.isAnimateing = false;
        });
    }else{
        [self.gifDic enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, FLAnimatedImageView * _Nonnull obj, BOOL * _Nonnull stop) {
            [obj stopAnimating];
        }];
        self.isAnimateing = false;
    }
}


- (void)imageViewClick:(UITapGestureRecognizer *)tap {
    UIView *imageView = tap.view;
    NSMutableArray *datas = [NSMutableArray array];
    [self.picPathStringsArray enumerateObjectsUsingBlock:^(URLModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 网络图片
        URLModel * model = (URLModel *)obj;
        YBIBImageData *data = [YBIBImageData new];
        data.imageURL = [NSURL URLWithString:model.momentUrl];
        [datas addObject:data];
    }];
    
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = datas;
    browser.currentPage = imageView.tag;
    browser.delegate = self;
    [browser show];
}



@end
